// Helene Martin, CSE 143 // Counts the occurrences of words in a large file and lets the // user ask how many times a given word occurred in the file. // It demonstrates the use of a Map collection. import java.io.*; import java.util.*; public class WordCount2 { public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); Map wordCounts = new TreeMap(); while (input.hasNext()) { String word = input.next().toLowerCase(); // when we get the value associated from a key that's not there, // we get null! Adding 1 to null causes an exception. // we therefore need to separate the cases where the key is already // in the map from the one where it's not. if (!wordCounts.containsKey(word)) { wordCounts.put(word, 1); } else { wordCounts.put(word, wordCounts.get(word) + 1); } } // iterate over the map using the set of keys for (String word : wordCounts.keySet()) { if (wordCounts.get(word) > 300) { // only display common words System.out.println(word + ": " + wordCounts.get(word)); } } } }